import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wu_you/data/cache/id_cache.dart';
import 'package:wu_you/data/repository/trad_repository.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/model/user/trad_model.dart';
import 'package:wu_you/page/dialog/input_dialog.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/state/bloc/http_bloc.dart';
import 'package:wu_you/state/bloc/trad_bloc.dart';
import 'package:wu_you/utils/input_util.dart';
import 'package:wu_you/utils/string_utils.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/widgets/http_status_widget.dart';
import 'package:wu_you/widgets/industry_checkbox.dart';
import 'package:wu_you/utils/extension_utils.dart';

///发布广告
class PublishPage extends StatefulWidget{
  final String wid;
  PublishPage({Key key,this.wid}):super(key: key);
  @override
  PublishPageState createState() => PublishPageState();
}
class PublishPageState extends State<PublishPage>{
  List<String> _tabs = [];

  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    _tabs.clear();
    _tabs = ['${message['trad39']}','${message['trad40']}'];
    return DefaultTabController(
      length: _tabs.length,
      child: Scaffold(
        appBar: AppBar(
          title: Text("${message['trad7']}"),
        ),
        backgroundColor: Colors.white,
        body: Column(
          children: [
            TabBar(
              labelColor: AppColors.primaryColor,
              indicatorColor: AppColors.primaryColor,
              unselectedLabelColor: AppColors.textHintColor,
              indicatorSize: TabBarIndicatorSize.label,
              unselectedLabelStyle: TextStyle(fontSize: 16),
              labelStyle: TextStyle(fontSize: 16,fontWeight: FontWeight.bold),
              indicatorPadding: EdgeInsets.all(5),
              tabs: _tabs.map((String c){
                return Tab(
                  text: c,
                );
              }).toList(),
            ),
            SizedBox(height: 2,),
            Divider(thickness: 5,color: HexColor("#F6F6F6"),),
            Expanded(
              child: HttpWidget<TradPubInfo, PublishInfoBloc>(
                create: (context) => PublishInfoBloc()..add(IdHttpEvent(int.parse(widget.wid))),
                child: (context, data) {
                  return TabBarView(
                    physics: NeverScrollableScrollPhysics(), //禁止滑动
                    children: [
                      _SellView(model: data,wid: widget.wid,),
                      _BuyView(model: data,wid: widget.wid,)
                    ]
                  );
                }
              )
            )
          ],
        ),
      )
    );
  }
}

///我要出售
class _SellView extends StatefulWidget{
  final TradPubInfo model;
  final String wid;
  _SellView({Key key,this.model,this.wid}):super(key: key);
  @override
  _SellViewState createState() => _SellViewState();
}
class _SellViewState extends State<_SellView>{
  TextStyle style = TextStyle(fontSize: 15,color: AppColors.textColor);
  TextEditingController _controller = TextEditingController();
  TextEditingController _controller1 = TextEditingController();
  String price;

  String inputNum;
  List<String> collection = ['微信','支付宝','银行卡'];

  String _select;

  String priceAll = '0.0';
  List<String> selectColl = [];

  var message;
  @override
  void initState() {
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return SingleChildScrollView(
      child: Column(
        children: [
          ListTile(
            leading: Text("${message['trad34']}",style: style,),
            title: Text("${widget.model.balance ?? 0}",style: Theme.of(context).textTheme.headline6,),
          ),
          Divider(),
          ListTile(
            leading: Text("${message['trad25']}",style: style,),
            title: Text("${widget.model.coin.consult_price ?? 0}",style: Theme.of(context).textTheme.headline6,),
          ),
          Divider(),
          ListTile(
            leading: Text("${message['trad26']}",style: TextStyle(fontSize: 15, ),),
            title: TextField(
              style: Theme.of(context).textTheme.headline6,
              maxLines: 1,
              textAlignVertical: TextAlignVertical.center,
              textInputAction: TextInputAction.next,
              autofocus: false,
              onChanged: (value) {
                this.price = value;
                if(price == null || price == ""){
                  price = "0";
                }
                if(_select != null){
                  priceAll = (double.parse(price) * double.parse(_select)).toStringAsFixed(2);
                }else{
                  priceAll = (double.parse('0.0') * double.parse('0.0')).toStringAsFixed(2);
                }
                setState(() {});
              },
              keyboardType: TextInputType.numberWithOptions(decimal: true),
              inputFormatters: [
                PrecisionLimitFormatter(4),
                FilteringTextInputFormatter.allow(RegExp('[0-9.,]+'))
              ],
              controller: _controller,
              decoration: InputDecoration(
                fillColor: Colors.transparent,
                prefixIconConstraints: BoxConstraints.loose(Size(80, 50)),
                filled: true,
                border: OutlineInputBorder(
                  borderSide: BorderSide.none,
                ),
                counterText: '',
                contentPadding: EdgeInsets.all(2),
                hintText: "${message['trad27']} (${widget.model.coin.min_price} - ${widget.model.coin.max_price})",
                hintStyle: Theme.of(context).textTheme.bodyText1,
              ),
            ),
          ),
          Divider(),

          widget.wid == "6"
          ? ListTile(
            leading: Text("${message['trad28']}",style: TextStyle(fontSize: 15, ),),
            title: TextField(
              style: Theme.of(context).textTheme.headline6,
              maxLines: 1,
              textAlignVertical: TextAlignVertical.center,
              textInputAction: TextInputAction.next,
              autofocus: false,
              onChanged: (value) {
                if(price != null){
                  priceAll = (double.parse(price) * double.parse(value)).toStringAsFixed(2);
                }
                setState(() {
                  _select = value;
                });
              },
              keyboardType: TextInputType.numberWithOptions(decimal: true),
              inputFormatters: [
                PrecisionLimitFormatter(4),
                FilteringTextInputFormatter.allow(RegExp('[0-9.,]+'))
              ],
              controller: _controller1,
              decoration: InputDecoration(
                fillColor: Colors.transparent,
                prefixIconConstraints: BoxConstraints.loose(Size(80, 50)),
                filled: true,
                border: OutlineInputBorder(
                  borderSide: BorderSide.none,
                ),
                counterText: '',
                contentPadding: EdgeInsets.all(2),
                hintText: "请输入数量",
                hintStyle: Theme.of(context).textTheme.bodyText1,
              ),
            ),
          )
          : Container(
            padding: EdgeInsets.only(left: 17,right: 15,top: 12,bottom: 12),
            child: Row(
              children: [
                Text("${message['trad28']}",style: style,),
                SizedBox(width: 20,),
                Expanded(
                    child: Wrap(
                      spacing: 12,
                      children: widget.model.coin.transaction_amount.map((e) {
                        return ChoiceChip(
                          elevation: 0,
                          padding: EdgeInsets.symmetric(horizontal: 4),
                          label: Text('$e', style: TextStyle(color: _select == e ? Colors.white : AppColors.textColor)),
                          selected: _select == e,
                          selectedColor: AppColors.primaryColor,
                          backgroundColor: HexColor("#EFEDED"),
                          onSelected: (v) {
                            if (_select == e) {
                              return;
                            }
                            if(price != null){
                              priceAll = (double.parse(price) * double.parse(e)).toStringAsFixed(2);
                            }
                            setState(() {
                              _select = e;
                            });
                          },
                        );
                      }).toList(),
                    )
                )
              ],
            ),
          ),
          Divider(),
          ListTile(
            leading: Text("${message['trad31']}",style: style,),
            title: Text("$priceAll",style: Theme.of(context).textTheme.headline6,),
          ),
          Divider(),

          Container(
            padding: EdgeInsets.only(left: 17,right: 15,top: 18,bottom: 18),
            child: Row(
              children: [
                Text("${message['trad33']}",style: style,),
                SizedBox(width: 20,),
                Expanded(
                    child: Wrap(
                      spacing: 12,
                      runSpacing: 6,
                      children: widget.model.payment.map((e){
                        return SelectPayType(name: e,addCallBack: (a){
                          if(!selectColl.contains(a)){
                            selectColl.add(a);
                            setState(() {});
                          }
                        },removeCallBack: (r){
                          if(selectColl.contains(r)){
                            selectColl.remove(r);
                            setState(() {});
                          }
                        },);
                      }).toList(),
                    )
                )
              ],
            ),
          ),
          Divider(),

          SizedBox(height: 30,),
          SizedBox(
            width: double.infinity,
            height: 42,
            child: ElevatedButton(
              child: Text("${message['trad35']}"),
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(AppColors.primaryColor),
                shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))),//圆角弧度
              ),
              onPressed: (){
                submit();
              },
            ),
          ).addPadding(EdgeInsets.only(left: 15,right: 15)),
        ],
      )
    );
  }

  void submit(){
    if(price == null){
      ToastUtils.show("${message['trad27']}", context);
      return;
    }
    if(_select == null){
      ToastUtils.show("${message['trad30']}", context);
      return;
    }
    if(selectColl.length == 0){
      ToastUtils.show("${message['trad45']}", context);
      return;
    }
    String s = selectColl.join(",");
    closeKeyboard(context);
    LoadingApi.func(TradRepository().publishAd(widget.wid, 1, _select, price,s), context,complete: (v){
      ToastUtils.show("${message['Success']}", context);
      Navigator.of(context).pop();
    },error: (e){
      ToastUtils.show("$e", context);
    });
  }
}



///我要购买
class _BuyView extends StatefulWidget{
  final TradPubInfo model;
  final String wid;
  _BuyView({Key key,this.model,this.wid}):super(key: key);
  @override
  _BuyViewState createState() => _BuyViewState();
}
class _BuyViewState extends State<_BuyView>{
  TextStyle style = TextStyle(fontSize: 15,color: AppColors.textColor);
  TextEditingController _controller = TextEditingController();
  TextEditingController _controller1 = TextEditingController();
  String price;

  String _select;
  String priceAll = '0.0';

  List<String> collection = ["1","2","3"];
  List<String> selectColl = [];

  var future;
  @override
  void initState() {
    super.initState();
    future = UserPhoneCache().get();
  }
  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return SingleChildScrollView(
      child: Column(
        children: [
          ListTile(
            leading: Text("${message['trad25']}",style: style,),
            title: Text("${widget.model.coin.consult_price ?? 0}",style: Theme.of(context).textTheme.headline6,),
          ),
          Divider(),
          ListTile(
            leading: Text("${message['trad26']}",style: TextStyle(fontSize: 15, ),),
            title: TextField(
              style: Theme.of(context).textTheme.headline6,
              maxLines: 1,
              textAlignVertical: TextAlignVertical.center,
              textInputAction: TextInputAction.next,
              autofocus: false,
              onChanged: (value) {
                this.price = value;
                if(price == null || price == ""){
                  price = "0";
                }
                if(_select != null){
                  priceAll = (double.parse(price) * double.parse(_select)).toStringAsFixed(2);
                }else{
                  priceAll = (double.parse('0.0') * double.parse('0.0')).toStringAsFixed(2);
                }
                setState(() {});
              },
              keyboardType: TextInputType.numberWithOptions(decimal: true),
              inputFormatters: [
                PrecisionLimitFormatter(4),
                FilteringTextInputFormatter.allow(RegExp('[0-9.,]+'))
              ],
              controller: _controller,
              decoration: InputDecoration(
                fillColor: Colors.transparent,
                prefixIconConstraints: BoxConstraints.loose(Size(80, 50)),
                filled: true,
                border: OutlineInputBorder(
                  borderSide: BorderSide.none,
                ),
                counterText: '',
                contentPadding: EdgeInsets.all(2),
                hintText: "${message['trad27']} (${widget.model.coin.min_price} - ${widget.model.coin.max_price})",
                hintStyle: Theme.of(context).textTheme.bodyText1,
              ),
            ),
          ),
          Divider(),

          widget.wid == "6"
          ? ListTile(
            leading: Text("${message['trad28']}",style: TextStyle(fontSize: 15, ),),
            title: TextField(
              style: Theme.of(context).textTheme.headline6,
              maxLines: 1,
              textAlignVertical: TextAlignVertical.center,
              textInputAction: TextInputAction.next,
              autofocus: false,
              onChanged: (value) {
                if(price != null){
                  priceAll = (double.parse(price) * double.parse(value)).toStringAsFixed(2);
                }
                setState(() {
                  _select = value;
                });
              },
              keyboardType: TextInputType.numberWithOptions(decimal: true),
              inputFormatters: [
                PrecisionLimitFormatter(4),
                FilteringTextInputFormatter.allow(RegExp('[0-9.,]+'))
              ],
              controller: _controller1,
              decoration: InputDecoration(
                fillColor: Colors.transparent,
                prefixIconConstraints: BoxConstraints.loose(Size(80, 50)),
                filled: true,
                border: OutlineInputBorder(
                  borderSide: BorderSide.none,
                ),
                counterText: '',
                contentPadding: EdgeInsets.all(2),
                hintText: "请输入数量",
                hintStyle: Theme.of(context).textTheme.bodyText1,
              ),
            ),
          )
          :Container(
            padding: EdgeInsets.only(left: 17,right: 15,top: 12,bottom: 12),
            child: Row(
              children: [
                Text("${message['trad28']}",style: style,),
                SizedBox(width: 20,),
                Expanded(
                    child: Wrap(
                      spacing: 12,
                      children: widget.model.coin.transaction_amount.map((e) {
                        return ChoiceChip(
                          elevation: 0,
                          padding: EdgeInsets.symmetric(horizontal: 4),
                          label: Text('$e', style: TextStyle(color: _select == e ? Colors.white : AppColors.textColor)),
                          selected: _select == e,
                          selectedColor: AppColors.primaryColor,
                          backgroundColor: HexColor("#EFEDED"),
                          onSelected: (v) {
                            if (_select == e) {
                              return;
                            }
                            if(price != null){
                              priceAll = (double.parse(price) * double.parse(e)).toStringAsFixed(2);
                            }
                            setState(() {
                              _select = e;
                            });
                          },
                        );
                      }).toList(),
                    )
                )
              ],
            ),
          ),


          Divider(),
          ListTile(
            leading: Text("${message['trad31']}",style: style,),
            title: Text("$priceAll",style: Theme.of(context).textTheme.headline6,),
          ),
          Divider(),
          Container(
            padding: EdgeInsets.only(left: 17,right: 15,top: 18,bottom: 18),
            child: Row(
              children: [
                Text("${message['trad84']}",style: style,),
                SizedBox(width: 20,),
                Expanded(
                    child: Wrap(
                      spacing: 12,
                      runSpacing: 6,
                      children: collection.map((e){
                        return SelectPayType(name: e,addCallBack: (a){
                          if(!selectColl.contains(a)){
                            selectColl.add(a);
                            setState(() {});
                          }
                        },removeCallBack: (r){
                          if(selectColl.contains(r)){
                            selectColl.remove(r);
                            setState(() {});
                          }
                        },);
                      }).toList(),
                    )
                )
              ],
            ),
          ),
          Divider(),
          SizedBox(height: 30,),

          FutureBuilder(
            future: future,
            builder: (context,data){
              String phone = data.data;
              if(phone != null && phone != ''){
                return SizedBox(
                  width: double.infinity,
                  height: 42,
                  child: ElevatedButton(
                    child: Text("${message['trad35']}"),
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(AppColors.primaryColor),
                      shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))),//圆角弧度
                    ),
                    onPressed: (){
                      submit();
                    },
                  ),
                ).addPadding(EdgeInsets.only(left: 15,right: 15));
              }else{
                return SizedBox(
                  width: double.infinity,
                  height: 42,
                  child: ElevatedButton(
                    child: Text("${message['trad35']}"),
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(AppColors.primaryColor),
                      shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))),//圆角弧度
                    ),
                    onPressed: (){
                      showDialog(
                        context: context,
                        builder: (context) => InputDialog(),
                      ).then((value){
                        future = UserPhoneCache().get();
                        setState(() {});
                      });
                      // submit();
                    },
                  ),
                ).addPadding(EdgeInsets.only(left: 15,right: 15));
              }
            }
          )
        ],
      ),
    );
  }
  void submit(){
    if(price == null){
      ToastUtils.show("${message['trad27']}", context);
      return;
    }
    if(_select == null){
      ToastUtils.show("${message['trad30']}", context);
      return;
    }
    if(selectColl.length == 0){
      ToastUtils.show("${message['trad118']}", context);
      return;
    }
    String s = selectColl.join(",");
    closeKeyboard(context);
    LoadingApi.func(TradRepository().publishAd(widget.wid, 2, _select, price,s), context,complete: (v){
      ToastUtils.show("${message['Success']}", context);
      Navigator.of(context).pop();
    },error: (e){
      ToastUtils.show("$e", context);
    });
  }
}






typedef AddCallBack = void Function(String item);
typedef RemoveCallBack = void Function(String item);
class SelectPayType extends StatefulWidget{
  final String name;
  final AddCallBack addCallBack;
  final RemoveCallBack removeCallBack;
  SelectPayType({Key key,this.name,this.addCallBack,this.removeCallBack}):super(key: key);
  @override
  SelectPayTypeState createState() => SelectPayTypeState();
}
class SelectPayTypeState extends State<SelectPayType>{
  bool _check = false;
  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        IndustryCheck(
          value: _check,
          onTap: (value){
            if(value){
              widget.addCallBack(widget.name);
            }else{
              widget.removeCallBack(widget.name);
            }
            setState(() {
              _check = value;
            });
          },
        ),
        SizedBox(width: 4,),
        Text("${showName(widget.name)}")
      ],
    );
  }

  String showName(e){
    switch(e){
      case "1":
        return "${message['trad36']}";
      case "2":
        return "${message['trad37']}";
      case "3":
        return "${message['trad38']}";
      case "4":
        return "USDT";
      case "5":
        return "TNG";
      default:
        return "";
    }
  }
}